package com.itboye.jigongbao.fragments.jiyibi_fragment

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.DatePickerDialog
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.provider.ContactsContract
import android.text.InputType.*
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.RelativeLayout
import android.widget.TextView
import com.itboye.jigongbao.R
import com.itboye.jigongbao.app.MyApplication
import com.itboye.jigongbao.base.BaseFragment
import com.itboye.jigongbao.bean.ContactBen
import com.itboye.jigongbao.bean.JiYiBiBean
import com.itboye.jigongbao.enums.DetailEnums
import com.itboye.jigongbao.retrofit.base.ResultEntity
import com.itboye.jigongbao.retrofit.presenter.UserPrestener
import com.itboye.jigongbao.utils.ByTimeUtils.timeFormat
import com.itboye.jigongbao.utils.Const
import com.itboye.jigongbao.utils.SPUtils
import com.itboye.jigongbao.utils.ToastUtil.ByAlert
import kotlinx.android.synthetic.main.jiyibi_fragment_diangong.*
import org.json.JSONObject
import java.util.*


/**
 * Created by Administrator on 2017/11/30.
 */
@SuppressLint("ValidFragment")
class JiGongFragment(private val jiyiBiType: DetailEnums) : BaseFragment(), Observer {


//    var type: DetailEnums? = null

//    init {
//        type = arguments.getSerializable("type")
//    }

    override fun update(p0: Observable?, p1: Any?) {

        var entity = p1 as ResultEntity
        when (entity.eventType) {
            UserPrestener.By_JgbRecord_add_Success -> {

            }
            UserPrestener.By_JgbRecord_add_Fail -> {

            }
            else -> {
            }
        }
        ByAlert.alert(entity.msg)
    }

    var txt_save_or_update: TextView? = null
    var alertDialog: AlertDialog? = null
    var type: String? = null

    var txt_date_value: TextView? = null//选择日期
    var txt_choose_contact_value: EditText? = null//选择通讯录工人
    var tv_choose_contact: TextView? = null
    var txt_gongzibiaozhun: EditText? = null//设置工资标准
    var txt_shangban_time_value: EditText? = null//上班时长
    var txt_jiaban_time_value: EditText? = null//加班时长
    var txt_project_name_value: EditText? = null//项目名称
    var edit_beizhu: EditText? = null//备注

    var contactNumer: String? = null//通讯录电话

    var GET_CONTACT: Int = 101

    var userPrestener: UserPrestener? = null
    //1. 类型(借支: 00S002004, 结算: 00S002005, 点工: 00S002003, 包工: 00S002002 )
    var recordType: String? = "00S002003"
    var model: JiYiBiBean.JiYiBiEntity? = null
    var re_choose_contact: RelativeLayout? = null
    override fun getLayoutId(): Int {
        return R.layout.jiyibi_fragment_diangong
    }

    override fun initData() {
        userPrestener = UserPrestener(this)
        type = arguments.getString("type")

        initRole()
        if (type.equals("update")) {
            txt_save_or_update!!.text = "修改"
            if (arguments.getSerializable("model") != null) {
                model = arguments.getSerializable("model") as JiYiBiBean.JiYiBiEntity
                setData()
            } else {
                model = null
            }
        } else {
            txt_save_or_update!!.text = "保存"
        }

//        initSpinner()
    }

    private fun setData() {
        if (model == null) {
            return
        }
        date = timeFormat("yyyyMMdd", "yyyy-MM-dd", model!!.daytime)
        txt_project_name_value!!.setText(model!!.project_title)
        txt_date_value!!.setText(date)
        date = timeFormat("yyyy-MM-dd", "yyyyMMdd", txt_date_value!!.text.toString())
        edit_beizhu!!.setText(model!!.note)
        when (jiyiBiType) {
            DetailEnums.YIJIBI_WORKER_DIANGONG -> {
                contactNumer = model!!.overseer_mobile
                txt_choose_contact_value!!.setText(model!!.overseer_name)
                var extra = model!!.extra
                var json = JSONObject(extra)
                if (json.has("hourly_wage")) {
                    txt_gongzibiaozhun!!.setText("${json.getDouble("hourly_wage") / 100}")
                }
                if (json.has("normal_worktime")) {
                    txt_shangban_time_value!!.setText(json.getString("normal_worktime"))
                }
                if (json.has("over_worktime")) {
                    txt_jiaban_time_value!!.setText(json.getString("over_worktime"))
                }
            }
            DetailEnums.YIJIBI_WORKER_BAOGONG -> {
                contactNumer = model!!.overseer_mobile
                txt_choose_contact_value!!.setText(model!!.overseer_name)
                var extra = model!!.extra
                var json = JSONObject(extra)
                txt_gongzibiaozhun!!.setText(model!!.sub_title)
                if (json.has("price")) {
                    txt_shangban_time_value!!.setText("${json.getString("price").toDouble() / 100}")
                }
                if (json.has("count")) {
                    txt_jiaban_time_value!!.setText(json.getString("count"))
                }
            }
            DetailEnums.YIJIBI_WORKER_JIEZHI -> {
                contactNumer = model!!.overseer_mobile
                txt_choose_contact_value!!.setText(model!!.overseer_name)
                txt_gongzibiaozhun!!.setText("${model!!.money / 100}")
            }
            DetailEnums.YIJIBI_WORKER_JIESUAN -> {
                contactNumer = model!!.overseer_mobile
                txt_choose_contact_value!!.setText(model!!.overseer_name)
                txt_gongzibiaozhun!!.setText("${model!!.money / 100}")
            }
        //-----------------工头
            DetailEnums.YIJIBI_FOREMAN_DIANGONG -> {
                contactNumer = model!!.worker_mobile
                txt_choose_contact_value!!.setText(model!!.worker_name)
                var extra = model!!.extra
                var json = JSONObject(extra)
                if (json.has("hourly_wage")) {
                    txt_gongzibiaozhun!!.setText("${json.getDouble("hourly_wage") / 100}")
                }
                if (json.has("normal_worktime")) {
                    txt_shangban_time_value!!.setText(json.getString("normal_worktime"))
                }
                if (json.has("over_worktime")) {
                    txt_jiaban_time_value!!.setText(json.getString("over_worktime"))
                }
            }
            DetailEnums.YIJIBI_FOREMAN_BAOGONG -> {
                contactNumer = model!!.worker_mobile
                txt_choose_contact_value!!.setText(model!!.worker_name)
                var extra = model!!.extra
                var json = JSONObject(extra)
                txt_gongzibiaozhun!!.setText(model!!.sub_title)
                if (json.has("price")) {
                    txt_shangban_time_value!!.setText("${json.getString("price").toDouble() / 100}")
                }
                if (json.has("count")) {
                    txt_jiaban_time_value!!.setText(json.getString("count"))
                }
            }
            DetailEnums.YIJIBI_FOREMAN_JIEZHI -> {
                contactNumer = model!!.worker_mobile
                txt_choose_contact_value!!.setText(model!!.worker_name)
                txt_gongzibiaozhun!!.setText("${model!!.money / 100}")
            }
            DetailEnums.YIJIBI_FOREMAN_JIESUAN -> {
                contactNumer = model!!.worker_mobile
                txt_choose_contact_value!!.setText(model!!.worker_name)
                txt_gongzibiaozhun!!.setText("${model!!.money / 100}")
            }
        }

    }

    private fun initRole() {
        var role = SPUtils.getSp(Const.ROLE) as String
        when (role) {
            Const.FORCEMAN -> {
                tv_choose_contact!!.text = "工人"
                txt_choose_contact_value!!.hint = "从通讯录选择工人"

            }
            Const.WORKER -> {
                tv_choose_contact!!.text = "工头"
                txt_choose_contact_value!!.hint = "从通讯录选择工头"
            }
        }
        when (jiyiBiType) {
            DetailEnums.YIJIBI_FOREMAN_DIANGONG, DetailEnums.YIJIBI_WORKER_DIANGONG -> {
                recordType = "00S002003"
                tr_forth.visibility = View.VISIBLE
                tr_fifth.visibility = View.VISIBLE
                tv_second.text = "工资标准"
                txt_gongzibiaozhun!!.hint = "设置工资标准"
                txt_gongzibiaozhun!!.inputType = TYPE_CLASS_NUMBER or TYPE_NUMBER_FLAG_DECIMAL
                tv_forth.text = "上班时长"
                txt_shangban_time_value!!.hint = "选择上班时长"
                txt_shangban_time_value!!.setText("0")
                fifth.text = "加班时长"
                txt_jiaban_time_value!!.hint = "选择加班时长"
                txt_jiaban_time_value!!.setText("0")
            }
            DetailEnums.YIJIBI_FOREMAN_BAOGONG, DetailEnums.YIJIBI_WORKER_BAOGONG -> {
                recordType = "00S002002"
                tr_forth.visibility = View.VISIBLE
                tr_fifth.visibility = View.VISIBLE
                tv_second.text = "分项名称"
                txt_gongzibiaozhun!!.hint = "输入项目名：如包转工，粉刷工"
                txt_gongzibiaozhun!!.inputType = TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_NORMAL
                tv_forth.text = "单价"
                txt_shangban_time_value!!.hint = "项目单价"
                fifth.text = "数量"
                txt_jiaban_time_value!!.hint = "输入数量"

            }
            DetailEnums.YIJIBI_FOREMAN_JIEZHI, DetailEnums.YIJIBI_WORKER_JIEZHI -> {
                recordType = "00S002004"
                tr_forth.visibility = View.GONE
                tr_fifth.visibility = View.GONE
                tv_second.text = "借支金额"
                txt_gongzibiaozhun!!.hint = "输入借支金额"
                txt_gongzibiaozhun!!.inputType = TYPE_CLASS_NUMBER or TYPE_NUMBER_FLAG_DECIMAL
            }
            DetailEnums.YIJIBI_FOREMAN_JIESUAN, DetailEnums.YIJIBI_WORKER_JIESUAN -> {
                recordType = "00S002005"
                tr_forth.visibility = View.GONE
                tr_fifth.visibility = View.GONE
                tv_second.text = "结算金额"
                txt_gongzibiaozhun!!.hint = "输入结算金额"
                txt_gongzibiaozhun!!.inputType = TYPE_CLASS_NUMBER or TYPE_NUMBER_FLAG_DECIMAL
            }
        }
        //工人记包工
        //工人记点工


        //工头记包工
        //工头记点工
    }

    fun initSpinner() {
        // 布局文件 R.layout.spinner_showed_item 决定了spinner中被显示出的那条的样式
        // 这个布局文件有一个默认安卓布局，名字叫做，自己写布局的时候不妨前去参考其中的各种要求
        // 例如必须是一个CheckedTextView 等等，事实上，顶多也就自己改一个背景图片之类的
        val adapter = object : ArrayAdapter<String>(activity, R.layout.spinner_option_items) {

            override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {

//                Log.w(TAG_CRY, "It is getView ing!")

//下面这句if似乎注释掉也不会产生影响
                //                if (position == getCount()) {
                //                    Log.w(TAG_CRY, "NOW : position == getCount()");
                //                    ((CheckedTextView)v.findViewById(R.id.spinner_showed_text)).setText("被显示的默认文字");
                //                    ((CheckedTextView)v.findViewById(R.id.spinner_showed_text)).setHint("被显示的默认提示"); //"Hint to be displayed"
                //                }
                return super.getView(position, convertView, parent)
            }

            override fun getCount(): Int {
//                Log.w(TAG_CRY, "获得getCount为：" + super.getCount())
                return super.getCount() - 1 // you don't display last item. It is used as hint.
            }

        }

        adapter.setDropDownViewResource(R.layout.spinner_option_items)
        adapter.add("1")
        adapter.add("2")
        adapter.add("3")

//      Spinner  spinner_gongtou.adapter = adapter
//        spinner_gongtou.setSelection(adapter.count) //display hint
    }

    override fun onClick(p0: View?) {
        when (p0!!.id) {
            R.id.txt_save_or_update -> {
                if (txt_save_or_update!!.text.equals("保存")) {
                    getTextValue(false)
                } else {
                    alertDialog = AlertDialog.Builder(activity, R.style.AlertDialog).create()
                    var view = View.inflate(activity, R.layout.popup_confirm_update, null)
                    alertDialog!!.setView(view)
                    alertDialog!!.show()
                    var txt_msg: TextView = view.findViewById(R.id.txt_msg)
                    txt_msg.setText("是否确认修改")
                    var txt_yes: TextView = view.findViewById(R.id.txt_yes)
                    var txt_no: TextView = view.findViewById(R.id.txt_no)
                    txt_yes.setOnClickListener(this)
                    txt_no.setOnClickListener(this)
                }
            }
            R.id.txt_yes -> {
                getTextValue(true)
            }
            R.id.txt_no -> {
                if (alertDialog!! != null) {
                    alertDialog!!.dismiss()
                }
            }
            R.id.txt_choose_contact_value, R.id.re_choose_contact -> {
                goToSelectContact()
            }
            R.id.txt_date_value -> {
                showDatePickDlg()
            }
            else -> {
            }
        }
    }

//    private fun requestRunPermission() {
//        var PERMISSIONS: Array<String> = arrayOf(Manifest.permission.READ_CONTACTS)
//        // 缺少权限时, 进入权限配置页面
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            requestRunPermisssion(PERMISSIONS, object : PermissionListener {
//                override fun onGranted() {
//                    //表示所有权限都授权了
////                    ByAlert.alert("所有权限都授权了，可以搞事情了")
//                    //我们可以执行打电话的逻辑
//                    //跳转通讯录
////                    goToSelectContact()
//                }
//
//                override fun onDenied(deniedPermission: List<String>) {
////                    for (permission in deniedPermission) {
////                        ByAlert.alert("被拒绝的权限：" + permission)
////                    }
////                    ByAlert.alert("被拒绝的权限：" + deniedPermission.toString())
////                    if (deniedPermission.isNotEmpty()) {
////                        showPermission(activity)
////                    }
//                }
//            })
//        } else {
//            goToSelectContact()
//        }
//    }

    fun goToSelectContact() {
        //跳转通讯录
        val uri = ContactsContract.Contacts.CONTENT_URI
        val intent = Intent(Intent.ACTION_PICK, uri)
        startActivityForResult(intent, GET_CONTACT)
    }

    private fun getTextValue(isUpdate: Boolean) {
        var manName = txt_choose_contact_value!!.text.toString()
        if (manName == null || "" == manName) {
            var role = SPUtils.getSp(Const.ROLE) as String
            when (role) {
                Const.FORCEMAN -> {
                    ByAlert.alert("请选择工人")

                }
                Const.WORKER -> {
                    ByAlert.alert("请选择工头")
                }
            }
            return
        }
        var gonzibiaozhun = txt_gongzibiaozhun!!.text.toString()//工资标准
        if (gonzibiaozhun == null || "" == gonzibiaozhun) {
            ByAlert.alert("请查看资料否填写完整")
            return
        }
        if (date == null) {
            ByAlert.alert("请选择日期")
            return
        }
        var shangban_times = txt_shangban_time_value!!.text.toString()
//        if (shangban_times == null || "" == shangban_times) {
//            ByAlert.alert("请注意资料完整")
//            return
//        }
        var jiaban_times = txt_jiaban_time_value!!.text.toString()
//        if (jiaban_times == null || "" == jiaban_times) {
//            ByAlert.alert("请注意资料完整")
//            return
//        }
        var project_name = txt_project_name_value!!.text.toString()
        if (project_name == null || "" == project_name) {
            ByAlert.alert("请填写所在项目")
            return
        }
        var note = edit_beizhu!!.text.toString()
//        if (note == null) {
//            ByAlert.alert("请填写备注信息")
//            return
//        }
        if (alertDialog != null) {
            alertDialog!!.dismiss()
        }

        when (jiyiBiType) {
            DetailEnums.YIJIBI_WORKER_DIANGONG -> {
                if (shangban_times == null || "" == shangban_times) {
                    shangban_times = "0"
                }
                if (jiaban_times == null || "" == jiaban_times) {
                    jiaban_times = "0"
                }
                if (!isUpdate) {
                    //添加操作
                    userPrestener!!.By_JgbRecord_add(
                            recordType,//记工类型
                            MyApplication.instance!!.loginInfo!!.getUid().toString(),//记录的用户id
                            MyApplication.instance!!.loginInfo!!.getMobile(),//工人手机号
                            MyApplication.instance!!.loginInfo!!.getRealName(),//工人姓名(1 - 20)
                            contactNumer,//工头手机号
                            manName,//工头姓名(1 - 20)
                            project_name,// 项目名称
                            null,//子项名称
                            note,// 备注(最大256个字符,一个中文计一个字符)
                            date,// 日期字符串格式(20171227)
                            -1.0,//金额(单位: 分)
                            -1.0,//单价(包工类型才需要传 单位: 分)
                            -1,//数量(包工类型才需要)
                            gonzibiaozhun.toDouble() * 100,// 时薪(单位: 元)[点工]
                            shangban_times,//上班时间(小时)[点工]
                            jiaban_times,//加班时长(小时)[点工]
                            activity)
                } else {
                    //修改操作
                    userPrestener!!.By_JgbRecord_update(MyApplication.instance!!.loginInfo!!.getUid().toString(),
                            model!!.id,
                            recordType,
                            MyApplication.instance!!.loginInfo!!.getMobile(),
                            MyApplication.instance!!.loginInfo!!.getRealName(),
                            contactNumer,
                            manName,
                            project_name,
                            null,
                            note,
                            date,
                            -1.0,
                            -1.0,
                            -1,
                            gonzibiaozhun.toDouble() * 100,
                            shangban_times,
                            jiaban_times,
                            activity)
                }
            }
            DetailEnums.YIJIBI_WORKER_BAOGONG -> {
                var price = txt_shangban_time_value!!.text.toString()
                var count = txt_jiaban_time_value!!.text.toString()
                if (price == null || "" == price) {
                    ByAlert.alert("请输入单价")
                    return
                }
                if (count == null || "" == count) {
                    ByAlert.alert("请输入数量")
                    return
                }
                if (!isUpdate) {
                    //添加操作
                    userPrestener!!.By_JgbRecord_add(
                            recordType,
                            MyApplication.instance!!.loginInfo!!.getUid().toString(),
                            MyApplication.instance!!.loginInfo!!.getMobile(),
                            MyApplication.instance!!.loginInfo!!.getRealName(),
                            contactNumer,
                            manName,
                            project_name,
                            gonzibiaozhun,
                            note,
                            date,
                            -1.0,
                            price.toDouble() * 100,
                            count.toInt(),
                            -1.0,
                            null,
                            null,
                            activity)
                } else {
                    //修改操作
                    userPrestener!!.By_JgbRecord_update(MyApplication.instance!!.loginInfo!!.getUid().toString(),
                            model!!.id,
                            recordType,
                            MyApplication.instance!!.loginInfo!!.getMobile(),
                            MyApplication.instance!!.loginInfo!!.getRealName(),
                            contactNumer,
                            manName,
                            project_name,
                            gonzibiaozhun,
                            note,
                            date,
                            -1.0,
                            price.toDouble() * 100,
                            count.toInt(),
                            -1.0,
                            shangban_times,
                            jiaban_times,
                            activity)
                }
            }
            DetailEnums.YIJIBI_WORKER_JIEZHI -> {
                if (!isUpdate) {
                    //添加操作
                    userPrestener!!.By_JgbRecord_add(
                            recordType,
                            MyApplication.instance!!.loginInfo!!.getUid().toString(),
                            MyApplication.instance!!.loginInfo!!.getMobile(),
                            MyApplication.instance!!.loginInfo!!.getRealName(),
                            contactNumer,
                            manName,
                            project_name,
                            null,
                            note,
                            date,
                            gonzibiaozhun.toDouble() * 100,
                            -1.0,
                            -1,
                            -1.0,
                            null,
                            null,
                            activity)
                } else {
                    //修改操作
                    userPrestener!!.By_JgbRecord_update(MyApplication.instance!!.loginInfo!!.getUid().toString(),
                            model!!.id,
                            recordType,
                            MyApplication.instance!!.loginInfo!!.getMobile(),
                            MyApplication.instance!!.loginInfo!!.getRealName(),
                            contactNumer,
                            manName,
                            project_name,
                            null,
                            note,
                            date,
                            gonzibiaozhun.toDouble() * 100,
                            -1.0,
                            -1,
                            -1.0,
                            null,
                            null,
                            activity)
                }
            }
            DetailEnums.YIJIBI_WORKER_JIESUAN -> {
                if (!isUpdate) {
                    //添加操作
                    userPrestener!!.By_JgbRecord_add(
                            recordType,
                            MyApplication.instance!!.loginInfo!!.getUid().toString(),
                            MyApplication.instance!!.loginInfo!!.getMobile(),
                            MyApplication.instance!!.loginInfo!!.getRealName(),
                            contactNumer,
                            manName,
                            project_name,
                            null,
                            note,
                            date,
                            gonzibiaozhun.toDouble() * 100,
                            -1.0,
                            -1,
                            -1.0,
                            null,
                            null,
                            activity)
                } else {
                    //修改操作
                    userPrestener!!.By_JgbRecord_update(MyApplication.instance!!.loginInfo!!.getUid().toString(),
                            model!!.id,
                            recordType,
                            MyApplication.instance!!.loginInfo!!.getMobile(),
                            MyApplication.instance!!.loginInfo!!.getRealName(),
                            contactNumer,
                            manName,
                            project_name,
                            null,
                            note,
                            date,
                            gonzibiaozhun.toDouble() * 100,
                            -1.0,
                            -1,
                            -1.0,
                            null,
                            null,
                            activity)
                }
            }
            DetailEnums.YIJIBI_FOREMAN_DIANGONG -> {
                if (shangban_times == null || "" == shangban_times) {
                    ByAlert.alert("请填写上班时间")
                    return
                }
                if (jiaban_times == null || "" == jiaban_times) {
                    ByAlert.alert("请填写加班时间")
                    return
                }
                if (!isUpdate) {
                    //添加操作
                    userPrestener!!.By_JgbRecord_add(
                            recordType,//记工类型
                            MyApplication.instance!!.loginInfo!!.getUid().toString(),//记录的用户id
                            contactNumer,//工头手机号
                            manName,//工头姓名(1 - 20)
                            MyApplication.instance!!.loginInfo!!.getMobile(),//
                            MyApplication.instance!!.loginInfo!!.getRealName(),//
                            project_name,// 项目名称
                            null,//子项名称
                            note,// 备注(最大256个字符,一个中文计一个字符)
                            date,// 日期字符串格式(20171227)
                            -1.0,//金额(单位: 分)
                            -1.0,//单价(包工类型才需要传 单位: 分)
                            -1,//数量(包工类型才需要)
                            gonzibiaozhun.toDouble() * 100,// 时薪(单位: 元)[点工]
                            shangban_times,//上班时间(小时)[点工]
                            jiaban_times,//加班时长(小时)[点工]
                            activity)
                } else {
                    //修改操作
                    userPrestener!!.By_JgbRecord_update(MyApplication.instance!!.loginInfo!!.getUid().toString(),
                            model!!.id,
                            recordType,
                            contactNumer,
                            manName,
                            MyApplication.instance!!.loginInfo!!.getMobile(),
                            MyApplication.instance!!.loginInfo!!.getRealName(),
                            project_name,
                            null,
                            note,
                            date,
                            -1.0,
                            -1.0,
                            -1,
                            gonzibiaozhun.toDouble() * 100,
                            shangban_times,
                            jiaban_times,
                            activity)
                }
            }
            DetailEnums.YIJIBI_FOREMAN_BAOGONG -> {
                var price = txt_shangban_time_value!!.text.toString()
                var count = txt_jiaban_time_value!!.text.toString()
                if (price == null || "" == price) {
                    ByAlert.alert("请输入单价")
                    return
                }
                if (count == null || "" == count) {
                    ByAlert.alert("请输入数量")
                    return
                }
                if (!isUpdate) {
                    //添加操作
                    userPrestener!!.By_JgbRecord_add(
                            recordType,
                            MyApplication.instance!!.loginInfo!!.getUid().toString(),
                            contactNumer,
                            manName,
                            MyApplication.instance!!.loginInfo!!.getMobile(),
                            MyApplication.instance!!.loginInfo!!.getRealName(),
                            project_name,
                            gonzibiaozhun,
                            note,
                            date,
                            -1.0,
                            price.toDouble() * 100,
                            count.toInt(),
                            -1.0,
                            null,
                            null,
                            activity)
                } else {
                    //修改操作
                    userPrestener!!.By_JgbRecord_update(MyApplication.instance!!.loginInfo!!.getUid().toString(),
                            model!!.id,
                            recordType,
                            contactNumer,
                            manName,
                            MyApplication.instance!!.loginInfo!!.getMobile(),
                            MyApplication.instance!!.loginInfo!!.getRealName(),
                            project_name,
                            gonzibiaozhun,
                            note,
                            date,
                            -1.0,
                            price.toDouble() * 100,
                            count.toInt(),
                            -1.0,
                            shangban_times,
                            jiaban_times,
                            activity)
                }
            }
            DetailEnums.YIJIBI_FOREMAN_JIEZHI -> {
                if (!isUpdate) {
                    //添加操作
                    userPrestener!!.By_JgbRecord_add(
                            recordType,
                            MyApplication.instance!!.loginInfo!!.getUid().toString(),
                            contactNumer,
                            manName,
                            MyApplication.instance!!.loginInfo!!.getMobile(),
                            MyApplication.instance!!.loginInfo!!.getRealName(),

                            project_name,
                            null,
                            note,
                            date,
                            gonzibiaozhun.toDouble() * 100,
                            -1.0,
                            -1,
                            -1.0,
                            null,
                            null,
                            activity)
                } else {
                    //修改操作
                    userPrestener!!.By_JgbRecord_update(MyApplication.instance!!.loginInfo!!.getUid().toString(),
                            model!!.id,
                            recordType,
                            contactNumer,
                            manName,
                            MyApplication.instance!!.loginInfo!!.getMobile(),
                            MyApplication.instance!!.loginInfo!!.getRealName(),

                            project_name,
                            null,
                            note,
                            date,
                            gonzibiaozhun.toDouble() * 100,
                            -1.0,
                            -1,
                            -1.0,
                            null,
                            null,
                            activity)
                }
            }
            DetailEnums.YIJIBI_FOREMAN_JIESUAN -> {
                if (!isUpdate) {
                    //添加操作
                    userPrestener!!.By_JgbRecord_add(
                            recordType,
                            MyApplication.instance!!.loginInfo!!.getUid().toString(),
                            contactNumer,
                            manName,
                            MyApplication.instance!!.loginInfo!!.getMobile(),
                            MyApplication.instance!!.loginInfo!!.getRealName(),
                            project_name,
                            null,
                            note,
                            date,
                            gonzibiaozhun.toDouble() * 100,
                            -1.0,
                            -1,
                            -1.0,
                            null,
                            null,
                            activity)
                } else {
                    //修改操作
                    userPrestener!!.By_JgbRecord_update(MyApplication.instance!!.loginInfo!!.getUid().toString(),
                            model!!.id,
                            recordType,
                            contactNumer,
                            manName,
                            MyApplication.instance!!.loginInfo!!.getMobile(),
                            MyApplication.instance!!.loginInfo!!.getRealName(),
                            project_name,
                            null,
                            note,
                            date,
                            gonzibiaozhun.toDouble() * 100,
                            -1.0,
                            -1,
                            -1.0,
                            null,
                            null,
                            activity)
                }
            }
        }
    }

    var date: String? = null
    protected fun showDatePickDlg() {
        val calendar = Calendar.getInstance()
        val datePickerDialog = DatePickerDialog(activity, DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
            txt_date_value!!.setText(year.toString() + "-" + (monthOfYear + 1) + "-" + dayOfMonth)
            date = timeFormat("yyyy-MM-dd", "yyyyMMdd", txt_date_value!!.text.toString())
//                birth = (date.time / 1000).toInt()
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH))
        datePickerDialog.show()

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == GET_CONTACT) {
            if (data == null) {
                return
            }
            //处理返回的data,获取选择的联系人信息
            val uri = data.data
            val contacts = getPhoneContacts(uri)

            txt_choose_contact_value!!.setText(contacts[0])
            contactNumer = contacts[1]
        }
    }

    /**
     * 获取联系人电话
     *
     * @param cursor
     * @param context
     * @return
     */
    private fun getContactPhone(cursor: Cursor, context: Context): ContactBen? {
        val vo = ContactBen()
        val phoneColumn = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)
        var phoneNum = 0
        try {
            phoneNum = cursor.getInt(phoneColumn)
        } catch (e: Exception) {
            return null
        }

        // String phoneResult = "";
        if (phoneNum > 0) {
            // 获得联系人的ID号
            val idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID)
            val contactId = cursor.getString(idColumn)

            vo.name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))

            // 获得联系人的电话号码的cursor;
            val phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null)

            if (phones.moveToFirst()) {
                // 遍历所有的电话号码
                while (!phones.isAfterLast()) {
                    val index = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                    val typeindex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE)
                    val phone_type = phones.getInt(typeindex)
                    val phoneNumber = phones.getString(index)
                    when (phone_type) {
                        2 -> vo.phone = phoneNumber
                    }
                    phones.moveToNext()
                }
                if (!phones.isClosed()) {
                    phones.close()
                }
            }
        }
        return vo
    }


    private fun getPhoneContacts(uri: Uri): Array<String?> {
        var contact = arrayOfNulls<String>(2)
//        val columns = arrayOf<String>(ContactsContract.Contacts.DISPLAY_NAME)
        //得到ContentResolver对象
        var cr = activity.getContentResolver()
        //取得电话本中开始一项的光标
        var cursor = cr.query(uri, null, null, null, null)
        if (cursor != null) {
            if (cursor.count > 0) {
                cursor!!.moveToFirst()
                //取得联系人姓名
//            for (i in 0 until cursor!!.columnCount) {
//                Log.v("tag", cursor!!.get)
//            }
                try {

                    var nameFieldColumnIndex = cursor!!.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)
                    contact[0] = cursor!!.getString(nameFieldColumnIndex)
                } catch (Ex: Exception) {
                    contact[0] = cursor!!.getString(0)
                }
                //取得电话号码
                var ContactId = cursor!!.getString(cursor!!.getColumnIndex(ContactsContract.Contacts._ID))
                var phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null)
                if (phone != null) {
                    phone!!.moveToFirst()
                    contact[1] = phone!!.getString(phone!!.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
                }
                phone!!.close()
                cursor!!.close()
            } else {
                ByAlert.alert("为0")
            }
        }
        return contact
    }
    /**
     * 命名

    类型

    获取值

    别名

    contactId

    Int

    cursor.getInt(4)

    ContactsContract.CommonDataKinds.Phone._ID

    联系人id

    displayName

    String

    cursor.getString(1)

    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME

    显示名，即姓名

    phoneNum

    String

    cursor.getString(2)

    ContactsContract.CommonDataKinds.Phone.CONTACT_ID

    电话号码

    sortKey

    String

    cursor.getString(3)

    ContactsContract.CommonDataKinds.Phone.DATA1, "sort_key"

    分类键

    photoId

    Long

    cursor.getLong(5)

    ContactsContract.CommonDataKinds.Phone.PHOTO_ID

    照片头像

    lookUpKey

    String

    cursor.getString(6)

    ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY

    lookUpKey

    formattedNumber

    String





    pinyin

    String



    姓名的中文拼音

    selected

    Int



    被选项
     */

    /**
     * none	0x00000000	There is no content type. The text is not editable.
     *text	0x00000001	Just plain old text. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_NORMAL.
     *textCapCharacters	0x00001001	Can be combined with text and its variations to request capitalization of all characters. Corresponds to TYPE_TEXT_FLAG_CAP_CHARACTERS.
     *textCapWords	0x00002001	Can be combined with text and its variations to request capitalization of the first character of every word. Corresponds to TYPE_TEXT_FLAG_CAP_WORDS.
     *textCapSentences	0x00004001	Can be combined with text and its variations to request capitalization of the first character of every sentence. Corresponds toTYPE_TEXT_FLAG_CAP_SENTENCES.
     *textAutoCorrect	0x00008001	Can be combined with text and its variations to request auto-correction of text being input. Corresponds to TYPE_TEXT_FLAG_AUTO_CORRECT.
     *textAutoComplete	0x00010001	Can be combined with text and its variations to specify that this field will be doing its own auto-completion and talking with the input method appropriately. Corresponds to TYPE_TEXT_FLAG_AUTO_COMPLETE.
     *textMultiLine	0x00020001	Can be combined with text and its variations to allow multiple lines of text in the field. If this flag is not set, the text field will be constrained to a single line. Corresponds to TYPE_TEXT_FLAG_MULTI_LINE.
     *textImeMultiLine	0x00040001	Can be combined with text and its variations to indicate that though the regular text view should not be multiple lines, the IME should provide multiple lines if it can. Corresponds to TYPE_TEXT_FLAG_IME_MULTI_LINE.
     *textNoSuggestions	0x00080001	Can be combined with text and its variations to indicate that the IME should not show any dictionary-based word suggestions. Corresponds toTYPE_TEXT_FLAG_NO_SUGGESTIONS.
     *textUri	0x00000011	Text that will be used as a URI. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_URI.
     *textEmailAddress	0x00000021	Text that will be used as an e-mail address. Corresponds toTYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_EMAIL_ADDRESS.
     *textEmailSubject	0x00000031	Text that is being supplied as the subject of an e-mail. Corresponds toTYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_EMAIL_SUBJECT.
     *textShortMessage	0x00000041	Text that is the content of a short message. Corresponds toTYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_SHORT_MESSAGE.
     *textLongMessage	0x00000051	Text that is the content of a long message. Corresponds toTYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_LONG_MESSAGE.
     *textPersonName	0x00000061	Text that is the name of a person. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_PERSON_NAME.
     *textPostalAddress	0x00000071	Text that is being supplied as a postal mailing address. Corresponds toTYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_POSTAL_ADDRESS.
     *textPassword	0x00000081	Text that is a password. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_PASSWORD.
     *textVisiblePassword	0x00000091	Text that is a password that should be visible. Corresponds toTYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_VISIBLE_PASSWORD.
     *textWebEditText	0x000000a1	Text that is being supplied as text in a web form. Corresponds toTYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_WEB_EDIT_TEXT.
     *textFilter	0x000000b1	Text that is filtering some other data. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_FILTER.
     *textPhonetic	0x000000c1	Text that is for phonetic pronunciation, such as a phonetic name field in a contact entry. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_PHONETIC.
     *textWebEmailAddress	0x000000d1	Text that will be used as an e-mail address on a web form. Corresponds toTYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS.
     *textWebPassword	0x000000e1	Text that will be used as a password on a web form. Corresponds toTYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_WEB_PASSWORD.
     *number	0x00000002	A numeric only field. Corresponds to TYPE_CLASS_NUMBER |TYPE_NUMBER_VARIATION_NORMAL.
     *numberSigned	0x00001002	Can be combined with number and its other options to allow a signed number. Corresponds to TYPE_CLASS_NUMBER | TYPE_NUMBER_FLAG_SIGNED.
     *numberDecimal	0x00002002	Can be combined with number and its other options to allow a decimal (fractional) number. Corresponds to TYPE_CLASS_NUMBER |TYPE_NUMBER_FLAG_DECIMAL.
     *numberPassword	0x00000012	A numeric password field. Corresponds to TYPE_CLASS_NUMBER |TYPE_NUMBER_VARIATION_PASSWORD.
     *phone	0x00000003	For entering a phone number. Corresponds to TYPE_CLASS_PHONE.
     *datetime	0x00000004	For entering a date and time. Corresponds to TYPE_CLASS_DATETIME |TYPE_DATETIME_VARIATION_NORMAL.
     *date	0x00000014	For entering a date. Corresponds to TYPE_CLASS_DATETIME |TYPE_DATETIME_VARIATION_DATE.
     *time	0x00000024	For entering a time. Corresponds to TYPE_CLASS_DATETIME |TYPE_DATETIME_VARIATION_TIME
     */
}